package com.pkche.core.advanced.extend;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

public class ControllerExceptionResolver extends SimpleMappingExceptionResolver {
	private final static Log logger = LogFactory.getLog(ControllerExceptionResolver.class);

	private String errorView;

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		String err = ex.getMessage();
		
		String msg = "";
		logger.error("系统错误：", ex);

//		Map<String, Object> context = new HashMap<String, Object>();
        if (ex instanceof RuntimeException) {
            msg = err == "" ? "系统错误，请与管理员联系。" : err;
        } else {
            msg = "系统错误，请与管理员联系" ;
        }

		String requestType = request.getHeader("X-REQUESTED-WITH");
		
		
		if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
			// ajax请求，不返回视图，使用输出流。
			try {
				response.setStatus(555);
				response.setContentType("application/json;charset=UTF-8");
				JSONObject json = new JSONObject();
				json.put("errorMsg", msg);
				response.getWriter().print(json.toString());
				response.getWriter().flush();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		} else {
			// 普通请求
			response.setContentType("text/html;charset=UTF-8");
			return new ModelAndView(errorView, null);
		}
	}

	public String getErrorView() {
		return errorView;
	}

	public void setErrorView(String errorView) {
		this.errorView = errorView;
	}
}
